import React, { useEffect, useState } from 'react';
import produce from 'immer';
import Table from '@/zero/components/Table';
import PubSub from 'pubsub-js';

/**
 * 简易 Table => 前端分页
 */
const Index = (props) => {
  const {
    name,

    defaultCurrent = 1,
    defaultPageSize = 10,
    pagination,

    rowNumber,
    columns = [],
    dataSource = [],
    onChange,
    ...rest
  } = props;

  const [current, setCurrent] = useState(defaultCurrent);
  const [pageSize, setPageSize] = useState(defaultPageSize);

  useEffect(() => {
    const token = PubSub.subscribe(
      name ? `SimpleTable[${name}].setCurrent` : `SimpleTable.setCurrent`,
      (_, newCurrent) => {
        setCurrent(newCurrent);
      },
    );
    return () => {
      if (token) {
        PubSub.unsubscribe(token);
      }
    };
  }, []);

  useEffect(() => {
    setCurrent(1);
  }, [dataSource]);

  const total = dataSource.length;

  const newCurrent = produce(current, (draftState) => {
    if (total) {
      const currentMax = Math.ceil(total / pageSize);
      if (draftState > currentMax) {
        draftState = currentMax;
      }
    }
    return draftState;
  });

  const newColumns = rowNumber
    ? [
        {
          title: 'No.',
          dataIndex: '_rowNumber',
          width: 70,
          render: (text, record, index) => (newCurrent - 1) * pageSize + index + 1,
          ...rowNumber,
        },
        ...columns,
      ]
    : columns;

  const newDataSource =
    pagination !== false
      ? dataSource.filter(
          (item, index) =>
            (newCurrent - 1) * pageSize < index + 1 && index + 1 <= newCurrent * pageSize,
        )
      : dataSource;

  return (
    <Table
      {...rest}
      columns={newColumns}
      dataSource={newDataSource}
      pagination={
        pagination !== false && {
          current: newCurrent,
          pageSize,
          total,
          ...pagination,
        }
      }
      onChange={(newPagination, newFilters, newSorter) => {
        if (Object.keys(newPagination).length) {
          const { current: nextCurrent, pageSize: nextPageSize } = newPagination;
          setCurrent(nextCurrent);
          setPageSize(nextPageSize);
        }
        if (onChange) {
          onChange(newPagination, newFilters, newSorter);
        }
      }}
    />
  );
};

Index.displayName = 'SimpleTable';
export default Index;
